# -*- coding: utf-8 -*-
"""
文本场景模板 - 专门用于文本展示
"""

from typing import Any, Dict, List, Optional
from pathlib import Path

from .base_template import BaseSceneTemplate


class TextSceneTemplate(BaseSceneTemplate):
    """文本场景模板"""

    def __init__(
        self,
        title: str = "",
        text: str = "",
        audio_duration: float = 0.0,
        subtitle_file: Optional[Path] = None,
        theme=None,
        layout: str = "center",  # center, left, split
        max_lines: int = 5,
    ):
        """
        初始化文本场景

        Args:
            title: 标题
            text: 文本内容
            audio_duration: 音频时长
            subtitle_file: 字幕文件
            theme: 主题
            layout: 布局方式
            max_lines: 最大行数
        """
        super().__init__(title, text, audio_duration, subtitle_file, theme)
        self.text = text
        self.layout = layout
        self.max_lines = max_lines

    def create_content(self, scene) -> Dict[str, Any]:
        """
        创建文本内容

        Args:
            scene: Manim场景对象

        Returns:
            包含标题和文本的字典
        """
        content = {}

        # 创建标题
        if self.title:
            title_style = self.get_style("title")
            title_obj = scene.Text(
                self.title,
                font_size=title_style["font_size"],
                color=title_style["color"],
                font=title_style["font"],
            )
            # 定位到顶部
            title_obj.to_edge(scene.UP, buff=self.get_position("safe_margin_y"))
            content["title"] = title_obj

        # 创建文本
        if self.text:
            text_style = self.get_style("content")
            text_obj = scene.Text(
                self.text,
                font_size=text_style["font_size"],
                color=text_style["color"],
                font=text_style["font"],
                line_spacing=1.5,  # 行间距
            )

            # 根据布局定位
            if self.layout == "center":
                text_obj.center()
            elif self.layout == "left":
                text_obj.to_edge(scene.LEFT, buff=1.0)
            elif self.layout == "split":
                # 如果有标题，文本放在标题下方
                if "title" in content:
                    text_obj.next_to(content["title"], scene.DOWN, buff=0.5)
                else:
                    text_obj.center()
            else:
                text_obj.center()

            # 限制最大宽度
            text_obj.set_max_width(self.get_position("max_text_width"))
            content["text"] = text_obj

        return content

    def animate_content(self, scene, content: Dict[str, Any]) -> None:
        """
        动画文本内容

        Args:
            scene: Manim场景对象
            content: 内容字典

        Returns:
            None
        """
        animations = []

        # 标题动画
        if "title" in content:
            title = content["title"]
            animations.append(scene.Write(title, run_time=self.get_animation_config("write_duration")))

        # 文本动画
        if "text" in content:
            text = content["text"]
            write_duration = self.get_animation_config("write_duration")

            # 如果文本较长，可以分段显示
            if len(self.text) > 100:
                # 分段显示，每20个字符一段
                chunk_size = 20
                text_parts = [self.text[i:i+chunk_size] for i in range(0, len(self.text), chunk_size)]

                for i, part in enumerate(text_parts):
                    part_style = self.get_style("content")
                    part_obj = scene.Text(
                        part,
                        font_size=part_style["font_size"],
                        color=part_style["color"],
                        font=part_style["font"],
                    )
                    part_obj.move_to(text.get_center())

                    if i == 0:
                        animations.append(scene.Write(part_obj, run_time=write_duration))
                    else:
                        animations.append(scene.FadeIn(part_obj, run_time=0.3))
            else:
                animations.append(scene.Write(text, run_time=write_duration))

        # 播放所有动画
        for anim in animations:
            scene.play(anim)

            # 如果使用了TimeScaler，等待相应时间
            if self.scaler:
                self.scaler.current_time += anim.run_time

    def get_scene_info(self) -> Dict[str, Any]:
        """
        获取场景信息

        Returns:
            场景信息字典
        """
        return {
            "type": "text",
            "title": self.title,
            "text_length": len(self.text),
            "layout": self.layout,
            "max_lines": self.max_lines,
            "estimated_duration": self.get_estimated_duration(),
        }
